import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'
import Home from '@/views/home/index.vue'
import useStore from '@/store'
const router = createRouter({
  history: createWebHashHistory(),
  // 路由跳转后滚动条到最上面
  scrollBehavior() {
    return {
      top: 0,
    }
  },
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    {
      path: '/playground',
      component: () => import('@/views/playground/index.vue'),
    },
    {
      path: '/login/callback',
      component: () => import('@/views/Login/callback.vue'),
    },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Home },
        {
          path: '/category/:id',
          component: () => import('@/views/category/index.vue'),
        },
        {
          path: '/category/sub/:id',
          component: () => import('@/views/category/sub.vue'),
        },
        {
          path: '/category/sub/:id',
          component: () => import('@/views/category/sub.vue'),
        },
        {
          path: '/goods/:id',
          component: () => import('@/views/goods/index.vue'),
        },
        {
          path: '/cart',
          component: () => import('@/views/cart/index.vue'),
        },
        {
          path: '/member/checkout',
          component: () => import('@/views/member/pay/checkout.vue'),
        },
        {
          path: '/member/pay',
          component: () => import('@/views/member/pay/index.vue'),
        },
        {
          path: '/pay/callback',
          component: () => import('@/views/member/pay/callback.vue'),
        },
        {
          path: '/member',
          component: () => import('@/views/member/layout/index.vue'),
          children: [
            {
              path: '',
              component: () => import('@/views/member/home/index.vue'),
            },
            {
              path: 'order',
              component: () => import('@/views/member/order/index.vue'),
            },
          ],
        },
      ],
    },
  ],
})
router.beforeEach((to, from, next) => {
  const { cart } = useStore()
  // 判断如果登录了
  if (cart.isLogin) {
    next() //直接放行
    // 没有登录
  } else {
    // 判断如果去member开头的页面
    if (to.fullPath.startsWith('/member')) {
      localStorage.setItem('checkoutPath', to.fullPath)
      next({
        path: '/login',
        /*query: {
          redirectUrl: to.fullPath,
        },可以通过传参的方式，拿到来的值，并且在登录时，跳转至来的路径,但是不适用于第三方登录，因为路径变了，找不到原来的路径了*/
      }) //放到登录页面去
    } else {
      next()
    }
  }
})
export default router
